/*
 * BackupDAO.java
 *
 * Created on March 22, 2007, 1:45 PM
 *
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.Cache;
import edu.byu.isys413.group1E.ConnectionPool;
import edu.byu.isys413.group1E.ConnectionPoolException;
import edu.byu.isys413.group1E.DataException;
import edu.byu.isys413.group1E.GUID;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/** This class is to read and write BackupBO information to and from the DB
 *
 * @author Travis Kulbeth
 */
public class BackupDAO extends RevenueSourceDAO{
    /** Contains an instance of BackupDAO*/
    private static BackupDAO instance = null;
    
    /** Creates a new instance of BackupDAO */
    public BackupDAO() {
    }
    
    /**Retrieves an instance of the TransactionDAO object
     *@return instance of BackupDAO
     */
    public static synchronized BackupDAO getInstance() {
        if (instance == null) {
            instance = new BackupDAO();
        }
        return instance;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /**
     * Creates a new BackupBO object with a newly generated GUID.
     * 
     * @return a newly created BackupBO with unique GUID
     * @throws java.lang.Exception to catch any errors in the creation process.
     */
    public RevenueSourceBO create() throws Exception{
        String id = GUID.generate();
        BackupBO bo = new BackupBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getRevSrcID(), bo);
        return bo;
    }
    
    /**
     * This is a public read statement.  It loads an existing Backup record
     * from the database based on the RevSrcID and returns a BackupBO.
     * 
     * @return a BackupBO containing the information extracted from the requested
     * tuple in the DB.
     * @param id contains the unique identifier for the record to be read from the DB.
     * @throws edu.byu.isys413.group1E.DataException to catch any errors with the incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException to catch errors when connecting to the DB
     */
     public RevenueSourceBO read(String id) throws SQLException, DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        BackupBO bu = (BackupBO)c.get(id);
        if (bu != null){
            return bu;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            bu = (BackupBO)this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return bu;
    }
    
    /**
     * This is a public read statement that is called after a connection has been established with the DB.
     * It loads an existing Backup record from the database based on the RevSrcID.
     *
     *This class calls its super class, RevenueSourceDAO, to read in the information that is common across
     *all Revenue Sources, then retrieves the unique information.
     * 
     * @return BackupBO
     * @param id contains the given id for the Backup to be read
     * @param conn contains an already open connection to the DB
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors with the connection
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    public synchronized RevenueSourceBO read(String id, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        BackupBO bu = (BackupBO)c.get(id);
        if (bu != null){
            return bu;                                                        // if so, return it immediately
        }
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        bu = new BackupBO(id);
        c.put(id, bu);
        bu = (BackupBO)super.read(id, conn);
        
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Backup_tbl WHERE RevenueSourceID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            bu.setBeginDate(rs.getDate("Begin_Date").toString());
            bu.setBuSize(rs.getDouble("BUSize"));
            bu.setEndDate(rs.getDate("End_Date").toString());
            bu.setAlreadyInDB(true);
            bu.setIsDirty(false);
            
            // save to the cache
            c.put(bu.getRevSrcID(), bu);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return bu;
    }
    
    /**This is a public method to retrieve a list of all Backup items in the DB.
     * 
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     * @return a list of all Backups from the DB.
     */
    public synchronized ArrayList<RevenueSourceBO> readAll() throws DataException, SQLException, ConnectionPoolException{
        ArrayList<RevenueSourceBO> list = new ArrayList<RevenueSourceBO>();
        //now build the query
        String query = "SELECT * FROM Backup_tbl";
        
        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        //build the object from the result set
        while (rs.next()) {
            BackupBO bu = new BackupBO(rs.getString("RevenueSourceID"));
            Cache.getInstance().put(rs.getString("RevenueSourceID"), bu);
            bu = (BackupBO)super.read(rs.getString("RevenueSourceID"), conn);
            bu.setBeginDate(rs.getDate("Begin_Date").toString());
            bu.setBuSize(rs.getDouble("BUSize"));
            bu.setEndDate(rs.getDate("End_Date").toString());
            bu.setAlreadyInDB(true);
            bu.setIsDirty(false);
            
            // save to the list
            list.add(bu);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return list;
    }
    
    /**
     * This method is really a part of save(bo, conn) in the super class.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     *This method is called by the save method in the super class after the common 
     *RS data has been saved to the DB.
     * 
     * @param bo contains the BackupBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors with the connection
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     */
    protected void update(RevenueSourceBO bo, Connection conn) throws SQLException, DataException {
        //update the DB
        BackupBO bu = (BackupBO)bo;
        PreparedStatement pstmt = conn.prepareStatement("UPDATE Backup_tbl SET Begin_Date = ?, End_Date = ?, BUSize = ? WHERE revenueSourceID = ?");
        
        pstmt.setDate(1, java.sql.Date.valueOf(bu.getBeginDate()));
        pstmt.setDate(2, java.sql.Date.valueOf(bu.getEndDate()));
        pstmt.setDouble(3, bu.getBuSize());
        pstmt.setString(4, bu.getRevSrcID());
        pstmt.executeUpdate();
        pstmt.close();
        bu.setAlreadyInDB(true);
    }// end update
    
    /**
     * This method is really a part of save(bo, conn) in the super class.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     *This method is called by the save method in the super class after the common 
     *RS data has been saved to the DB.
     * 
     * @param bo contains the BackupBO to be inserted into the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors with the connection
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     */
    synchronized void insert(RevenueSourceBO bo, Connection conn) throws SQLException, DataException {
        //update the DB
        BackupBO bu = (BackupBO)bo;
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Backup_Tbl (revenueSourceID, Begin_Date, " +
                "End_Date, BuSize) VALUES (?, ?, ?, ?)");
        pstmt.setString(1, bu.getRevSrcID());
        pstmt.setDate(2, java.sql.Date.valueOf(bu.getBeginDate()));
        pstmt.setDate(3, java.sql.Date.valueOf(bu.getEndDate()));
        pstmt.setDouble(4, bu.getBuSize());
        pstmt.executeUpdate();
        pstmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        bu.setAlreadyInDB(true);
    }//end insert
}
